package com.leicx.guli.auth.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.leicx.guli.auth.feign.MemberFeignService;
import com.leicx.guli.auth.feign.ThirdPartyFeignService;
import com.leicx.guli.auth.vo.UserLoginVo;
import com.leicx.guli.auth.vo.UserRegisterVo;
import com.leicx.guli.common.constant.AuthServerConstant;
import com.leicx.guli.common.enums.GuliExceptionEnum;
import com.leicx.guli.common.exception.RRException;
import com.leicx.guli.common.utils.FeignUtil;
import com.leicx.guli.common.utils.R;
import com.leicx.guli.common.vo.MemberResponseVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author daxiong
 * @date 2022/7/26 上午11:38
 */
@Controller
public class LoginController {

    @Resource
    ThirdPartyFeignService thirdPartyFeignService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    MemberFeignService memberFeignService;

    private static final int CODE_EXPIRE_TIME = 60 * 1000;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // 1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StrUtil.isNotBlank(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < CODE_EXPIRE_TIME) {
                // 60s内不能再刷
                throw new RRException(GuliExceptionEnum.SMS_CODE_EXCEPTION);
            }
        }
        // 2、redis存key-value，value为：code_时间戳
        String realCode = IdUtil.fastSimpleUUID().substring(0, 4);
        redisCode = realCode + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(
                AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redisCode, 15, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, realCode);
        return R.ok();
    }

    /**
     * RedirectAttributes 重定向携带数据
     * 存在的问题：
     * RedirectAttributes 重定向携带数据，利用的原理是，将数据放在session中。
     * 只要跳到下一个页面取出这个数据后，session里面的数据就会删掉。这个session只能用于单机服务中。
     * // TODO: 2022/7/28 1.分布式下的session问题。
     *
     * @param userRegisterVo
     * @param result
     * @param model
     * @return java.lang.String
     * @author daxiong
     * @date 2022/7/28 上午10:13
     */
    @PostMapping("/register")
    public String register(@Validated UserRegisterVo userRegisterVo, BindingResult result,
                           Model model, RedirectAttributes redirectAttributes) {
        Map<String, String> errors;
        if (result.hasErrors()) {
            errors = result.getFieldErrors()
                    .stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            /**
             * 1、校验出错，转发到注册页，用转发会报错：Request method 'POST' not supported
             *    是因为本方法是post请求，但是转发到"/reg.html"，路径映射默认都是get方式访问的，所以会报错
             * 2、使用重定向，要注意数据携带问题，使用RedirectAttributes，原理是session
             *    同时重定向要写完整的域名
             */
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验验证码
        String code = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if (StrUtil.isNotEmpty(code) && userRegisterVo.getCode().equals(code.split("_")[0])) {
            // 删除验证码
            stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
            // 验证码通过，调用远程服务进行注册
            R register = memberFeignService.register(userRegisterVo);
            if (register.success()) {
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                errors = new HashMap<>();
                errors.put("msg", (String) register.get("msg"));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        // 远程登录
        R result = memberFeignService.login(vo);
        if (result.success()) {
            MemberResponseVo responseVo = FeignUtil.formatClass(result, MemberResponseVo.class);
            // 放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER, responseVo);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) result.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (Objects.isNull(loginUser)) {
            // 没登录
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

}
